package handler

import (
	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
	"log"
	"rbook/pkg"
	"sync"
)

//import "github.com/gorilla/websocket"

type Message struct {
	UserId string `json:"userId" form:"userId" binding:"required"`
	SendId string `json:"sendId" form:"sendId" binding:"required"`
}
type Node struct {
	Conn *websocket.Conn
	Data chan []byte
}

var ClineMap = make(map[string]*Node, 0)
var wsg sync.WaitGroup

func Chant(c *gin.Context) {
	var chat Message
	c.ShouldBind(&chat)

	id := chat.UserId
	sendId := chat.SendId

	msg := &Message{
		UserId: id,
		SendId: sendId,
	}

	upgrader := websocket.Upgrader{
		ReadBufferSize:  1024,
		WriteBufferSize: 1024,
	}

	upgrade, err := upgrader.Upgrade(c.Writer, c.Request, nil)
	if err != nil {
		return
	}

	node := &Node{
		Conn: upgrade,
		Data: make(chan []byte, 100),
	}

	ClineMap[id+"_"+sendId] = node
	wsg.Add(4)
	go revoer(node, msg)
	go send(node, msg)
}
func revoer(node *Node, msg *Message) {
	defer wsg.Done()
	for {
		_, message, _ := node.Conn.ReadMessage()
		check, _ := pkg.Baidu(string(message))
		log.Println(check)
		if !check {
			err := node.Conn.WriteMessage(websocket.TextMessage, []byte("敏感词不能发送"))
			if err != nil {
				return
			}
			continue
		}

		tr, ex := ClineMap[msg.SendId+"_"+msg.UserId]
		if ex {
			tr.Data <- message
		}
	}
}
func send(node *Node, msg *Message) {
	defer wsg.Done()
	for {
		select {
		case data := <-node.Data:
			err := node.Conn.WriteMessage(websocket.TextMessage, data)
			if err != nil {
				panic("发送失败")
				return
			}
		}
	}
}
